package com.gxa.medical.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.gxa.medical.config.AlipayConfig;
import com.gxa.medical.pojo.User;
import com.gxa.medical.service.UserService;
import com.gxa.medical.util.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;

@RestController
public class AlipayController {
    @Autowired
    private UserService userService;
    @RequestMapping("/alipay")
    public void alipay(HttpServletResponse httpResponse, HttpServletRequest request, HttpSession session) throws IOException {
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id,
                AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);
        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(AlipayConfig.return_url);
        alipayRequest.setNotifyUrl(AlipayConfig.notify_url);
        String WIDsubject = "xkhnlhml";
        String WIDbody = "充值界面";
//        Map<String, Object> objectMap = new HashMap<String, Object>();
//        objectMap.put("price", request.getParameter("productTotalPrice"));
//        session.setAttribute("payInfo", objectMap);
        //商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no = UUID.randomUUID().toString().replaceAll("-", "");
//        		new String(request.getParameter("ids").getBytes("ISO-8859-1"),"UTF-8");
        //付款金额，必填
         String many = new String(request.getParameter("money").getBytes("ISO-8859-1"), "UTF-8");
         session.setAttribute("many",many);
        String phone = new String(request.getParameter("phone").getBytes("ISO-8859-1"), "UTF-8");
        session.setAttribute("phone",phone);
        //订单名称，必填
        String subject = new String(WIDsubject.getBytes("ISO-8859-1"), "UTF-8");
        //商品描述，可空
        String body = new String(WIDbody.getBytes("ISO-8859-1"), "UTF-8");

        alipayRequest.setBizContent("{\"out_trade_no\":\"" + out_trade_no + "\","
                + "\"total_amount\":\"" + many + "\","
                + "\"subject\":\"" + subject + "\","
                + "\"body\":\"" + body + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

        //若想给BizContent增加其他可选请求参数，以增加自定义超时时间参数timeout_express来举例说明
        //alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
        //		+ "\"total_amount\":\""+ total_amount +"\","
        //		+ "\"subject\":\""+ subject +"\","
        //		+ "\"body\":\""+ body +"\","
        //		+ "\"timeout_express\":\"10m\","
        //		+ "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        //请求参数可查阅【电脑网站支付的API文档-alipay.trade.page.pay-请求参数】章节

        //请求
        String result = "";
        try {
            // 调用SDK生成表单
            result = alipayClient.pageExecute(alipayRequest).getBody();
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }

        httpResponse.setContentType("text/html;charset=" + AlipayConfig.charset);
        // 直接将完整的表单html输出到页面
        httpResponse.getWriter().write(result);
        httpResponse.getWriter().flush();
        httpResponse.getWriter().close();
    }


    /**
     * 注意异步返回结果通知是以post请求形式返回的
     *
     * @param request
     * @return
     */
    @RequestMapping("notifyUrl")
    public String notify_url(HttpSession session, HttpServletRequest request) throws Exception {
        String flag="1";
        JsonResult jsonResult = new JsonResult();
        Map<String, String> paramsMap = convertRequestParamsToMap(request);
        String out_trade_no = paramsMap.get("out_trade_no");
        String tradeStatus = paramsMap.get("trade_status");
        try {
            boolean signVerified = AlipaySignature.rsaCheckV1(paramsMap, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type);
            //无论同步异步都要验证签名
            if (signVerified) {
                if (tradeStatus.equals("TRADE_FINISHED") || tradeStatus.equals("TRADE_SUCCESS")) {
                    String phone = (String)session.getAttribute("phone");
                    String many = (String) session.getAttribute("many");
                    User user = userService.selectMany(phone);
                    userService.updateMany((Integer.parseInt(many)+user.getMoney()),phone);
                    System.err.println(Integer.parseInt(many)+user.getMoney());
                   flag="1";
                }
            } else {
                //签名验证失败不处理业务逻辑
                flag="0";
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return flag;
    }

    //注意同步返回结果是以get请求形式返回的
    @RequestMapping("returnUrl")
    public String return_url(HttpServletRequest request) throws Exception {
        String flag="1";
        JsonResult jsonResult = new JsonResult();
        Map<String, String> paramsMap = convertRequestParamsToMap(request);
        try {
            boolean signVerified = AlipaySignature.rsaCheckV1(paramsMap, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type);
            if (signVerified) {

                HttpSession session = request.getSession();
                String phone = (String)session.getAttribute("phone");
                User user = userService.selectMany(phone);
                String many = (String) session.getAttribute("many");
                userService.updateMany((Integer.parseInt(many)+user.getMoney()),phone);
                System.err.println(Integer.parseInt(many)+user.getMoney());
                flag="1";
            } else {
                //跳转支付失败界面
               flag="0";
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return flag;
    }


    //将请求中的参数转换为Map
    public static Map<String, String> convertRequestParamsToMap(HttpServletRequest request) {
        Map<String, String> retMap = new HashMap();
        Set<Map.Entry<String, String[]>> entrySet = request.getParameterMap().entrySet();
        Iterator var3 = entrySet.iterator();

        while (true) {
            while (var3.hasNext()) {
                Map.Entry<String, String[]> entry = (Map.Entry) var3.next();
                String name = (String) entry.getKey();
                String[] values = (String[]) entry.getValue();
                int valLen = values.length;
                if (valLen == 1) {
                    retMap.put(name, values[0]);
                } else if (valLen <= 1) {
                    retMap.put(name, "");
                } else {
                    StringBuilder sb = new StringBuilder();
                    String[] var9 = values;
                    int var10 = values.length;

                    for (int var11 = 0; var11 < var10; ++var11) {
                        String val = var9[var11];
                        sb.append(",").append(val);
                    }

                    retMap.put(name, sb.toString().substring(1));
                }
            }

            return retMap;
        }
    }

    //将字符串转换为UTF-8编码以防出现乱码错误
    public static String getUTF8XMLString(String xml) {
        StringBuffer sb = new StringBuffer();
        sb.append(xml);
        String xmString = "";
        String xmlUTF8 = "";
        try {
            xmString = new String(sb.toString().getBytes("UTF-8"));
            xmlUTF8 = URLEncoder.encode(xmString, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return xmlUTF8;
    }


}
